package com.zp.service;

import com.zp.api.ApiCode;
import com.zp.api.ApiResult;
import com.zp.domain.ConfigInfo;
import com.zp.dto.request.ConfigReq;
import com.zp.mapper.ConfigInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zp
 * @description 配置服务service
 * @created 2021/12/1 14:25
 */

@RestController
@RequestMapping("/config")
public class ConfigServerService {

    @Autowired
    private ConfigInfoMapper configInfoMapper;
    /**
     * 新增配置
     * @return
     */
    @PostMapping("/addConfig")
    public ApiResult addConfig(@RequestBody ConfigReq configReq){
        ConfigInfo configInfo = new ConfigInfo();
        configInfo.setContent(configReq.getContent()).setDataId(configReq.getDataId());
        configInfo.setMd5(DigestUtils.md5DigestAsHex(configReq.getContent().getBytes()));
        return configInfoMapper.addConfig(configInfo)?ApiResult.ok():ApiResult.fail(ApiCode.FAIL);
    }

    /**
     * 更新配置
     * @return
     */
    @PostMapping("/updateConfig")
    public ApiResult updateConfig(@RequestBody ConfigReq configReq){
        ConfigInfo configInfo = new ConfigInfo();
        configInfo.setContent(configReq.getContent()).setDataId(configReq.getDataId());
        configInfo.setMd5(DigestUtils.md5DigestAsHex(configReq.getContent().getBytes()));
        return configInfoMapper.updateConfig(configInfo)?ApiResult.ok():ApiResult.fail(ApiCode.FAIL);
    }

    /**
     * 根据服务名称获取配置文件
     * @return
     */
    @GetMapping("/getConfig")
    public ApiResult getConfig(@RequestParam String dataId){
        ConfigInfo configInfo  = configInfoMapper.getConfig(dataId);
        return ApiResult.ok(configInfo);
    }

    /**
     * 根据服务名称+md5检查md5是否过期
     * @return
     */
    @GetMapping("/checkConfig")
    public ApiResult checkConfig(@RequestParam String dataId,@RequestParam String md5){
        ConfigInfo configInfo  = configInfoMapper.checkConfig(dataId,md5);
        if(configInfo == null){
            configInfo = configInfoMapper.getConfig(dataId);
            return ApiResult.fail(ApiCode.FAIL,configInfo);
        }
        return ApiResult.ok();
    }

    /**
     * 获取所有的配置
     * @return
     */
    @GetMapping("/getAllConfig")
    public ApiResult getAllConfig(){
        List<ConfigInfo> configInfos = configInfoMapper.getAllConfig();
        return ApiResult.ok(configInfos);
    }
}
